/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import httpclient from '@ohos/httpclient';
import router from '@system.router';
import Author from '../../model/author';
import Log from '../../log/log';
import http from '@ohos.net.http';
import fileIO from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility'


export default {
    data: {
        status: "",
        content: "",
        echoServer: "http://www.yourserverfortest.com",
        commonServer: "http://www.yourserverforcommontest.com",
        fileName: "/test.txt",
        client: new httpclient.HttpClient
        .Builder()
            .setConnectTimeout(10000)
            .setReadTimeout(10000)
            .build(),
        cookiejar : new httpclient.CookieJar(),
        cookiemanager : new httpclient.CookieManager(),
        store : new httpclient.CookieStore()
    },
    onInit() {
            this.cookiemanager.setCookiePolicy(httpclient.CookiePolicy.ACCEPT_ALL);
           },
    showIndexView() {
        router.push({
            uri: 'pages/index/index'
        })
    },
    onComplete: function (result) {
        if (result.response) {
            this.status = result.response.responseCode;
        }
        if (result.response.result)
            this.content = result.response.result;
        else
            this.content = JSON.stringify(result.response);

        Log.showInfo("onComplete -> Content : " + JSON.stringify(this.content));
    },
    onError: function (error) {
        Log.showInfo("onError -> Error : " + error);
        this.content = JSON.stringify(error);
        Log.showInfo("onError -> Content : " + JSON.stringify(this.content));
    },
    onComplete1: function (result) {
        if (result.response) {
            this.status = result.response.responseCode;
        }
        if (result.response.result)
            this.content = result.response.result;
        else
            this.content = JSON.stringify(result.response);

        Log.showInfo("onComplete1 -> Content : " + JSON.stringify(this.content));
    },
    onError1: function (error) {
        Log.showInfo("onError1 -> Error : " + error);
        this.content = JSON.stringify(error);
    },
    onComplete2: function (result) {
        if (result.response) {
            this.status = result.response.responseCode;
        }
        if (result.response.result)
            this.content = result.response.result;
        else
            this.content = JSON.stringify(result.response);

        Log.showInfo("onComplete2 -> Content : " + JSON.stringify(this.content));
    },
    onError2: function (error) {
        Log.showInfo("onError2 -> error : " + error);
        this.content = JSON.stringify(error);
    },
    onComplete3: function (result) {
        if (result.response) {
            this.status = result.response.responseCode;
        }
        Log.showInfo("onComplete3 -> Status : " + this.status);

        if (result.response.result)
            this.content = result.response.result;
        else
            this.content = JSON.stringify(result.response);

        Log.showInfo("onComplete3 -> Content : " + JSON.stringify(this.content));
    },
    onError3: function (error) {
        Log.showInfo("onError3 -> error : " + error);
        this.content = JSON.stringify(error);
    },

    onComplete4: function (result) {
        if (result.response) {
            this.status = result.response.responseCode;
        }
        if (result.response.result)
            this.content = result.response.result;
        else
            this.content = JSON.stringify(result.response);

        Log.showInfo("onComplete4 -> Content : " + JSON.stringify(this.content));
    },
    onError4: function (error) {
        Log.showInfo("onError4 -> error : " + error);
        this.content = JSON.stringify(error);
    },
    timeoutRequest() {
        this.content = "waiting for response";
        let request1 = new httpclient.Request.Builder()
            .get(this.commonServer)
            .tag("tag_timeout")
            .addHeader("Content-Type", "application/json")
            .build();
        this.client.newCall(request1).enqueue(this.onComplete, this.onError);
    },
    async uploadRequest() {
        Log.showInfo("uploadRequest ->  : " );
        let appInternalDir;
        // @ts-ignore
        var fAbility = featureAbility.getContext().getCacheDir();
        await fAbility.then(function (result) {
            appInternalDir = result;
        });
        Log.showInfo("appInternalDir ->  : " + appInternalDir);
        let fpath = appInternalDir + this.fileName;
        let fd = fileIO.openSync(fpath, 0o102, 0o666);
        Log.showInfo("file opened  ->  : " + fpath);
        // @ts-ignore
        fileIO.writeSync(fd, "text.txt file is uploaded", function (err, bytesWritten) {
        });
        fileIO.closeSync(fd);
        Log.showInfo("file closed  ->  : " + fpath);
        fpath = fpath.replace(appInternalDir, "internal://cache");
        Log.showInfo("fpath ->  : " + fpath);
        var fileUploadBuilder = new httpclient.FileUpload.Builder()
            .addFile(fpath)
            .addData("name2", "value2")
            .build();
        var fileObject = fileUploadBuilder.getFile();
        var dataObject = fileUploadBuilder.getData();
        let request = new httpclient.Request.Builder()
            .url(this.commonServer)
            .addFileParams(fileObject, dataObject)
            .build();
        this.client.newCall(request)
            .execute()
            .then(this.onComplete)
            .catch(this.onError);
        Log.showInfo("file upload request ->  : " + dataObject);

    },
    simpleRequest() {
        Log.showInfo("http simple request sending ");
        this.content = "waiting for response";
        let httpRequest= http.createHttp();
        httpRequest.request(this.commonServer,
            {
                method: 'GET',
                header: {
                    'Content-Type': 'application/json'
                },
                readTimeout: 10000,
                connectTimeout: 10000
            },(err, data) => {
                Log.showInfo("http simple request got response ");
                if (!err) {
                    this.content = data.result +", code : "+data.responseCode+",header:"+data.header;
                    Log.showInfo("http simple request  success->  : " + this.content);
                } else {
                    this.content = err.data +', code :'+err.code;
                    Log.showInfo("http simple request  error->  : " + this.content);
                }
            });
    },
    cookieRequest() {
        Log.showInfo("http cookiejarRequest request sending ");
        var self  = this;
        this.cookiemanager.setCookiePolicy(httpclient.CookiePolicy.ACCEPT_ALL);
        this.cookiejar.setCookieStore(this.store);
                //first request to get the cookie
        let request1 = new httpclient.Request.Builder()
                    .get(this.commonServer)
                    .tag("tag_cookie1")
                    .cookieJar(this.cookiejar)
                    .cookieManager(this.cookiemanager)
                    .addHeader("Content-Type", "application/json")
                    .build();
        self.client.newCall(request1).enqueue(this.onComplete, this.onError);
    },
    cookieRequest1() {
        Log.showInfo("http cookiejarRequest request sending ");
        var self  = this;
        this.cookiemanager.setCookiePolicy(httpclient.CookiePolicy.ACCEPT_ALL);
        this.cookiejar.setCookieStore(this.store);
                //first request to get the cookie
        let request1 = new httpclient.Request.Builder()
                    .get(this.commonServer) //Modify URL
                    .tag("tag_cookie1")
                    .cookieJar(this.cookiejar)
                    .cookieManager(this.cookiemanager)
                    .addHeader("Content-Type", "application/json")
                    .build();
        self.client.newCall(request1).enqueue(this.onComplete, this.onError);
    }
    ,
    cookieRequest2() {
        Log.showInfo("http cookiejarRequest request sending ");
        var self  = this;
        this.cookiemanager.setCookiePolicy(httpclient.CookiePolicy.ACCEPT_ORIGINAL_SERVER);
        this.cookiejar.setCookieStore(this.store);
        let request1 = new httpclient.Request.Builder()
                    .get(this.commonServer)
                    .tag("tag_cookie2")
                    .cookieJar(this.cookiejar)
                    .cookieManager(this.cookiemanager)
                    .addHeader("Content-Type", "application/json")
                    .build();
        self.client.newCall(request1).enqueue(this.onComplete, this.onError);
    },

    customRequest() {
        var authorId = "abc7689"
        var userName = "TestUser";
        var emailId = "testmail@gmail.com";
        var password = "password123";
        var author = new Author(authorId, userName, emailId, password);

        let requestBody = httpclient.RequestBody.create(JSON.stringify(author))

        var request = new httpclient.Request.Builder()
            .url("https://postman-echo.com/post")
            .post(requestBody)
            .addHeader("Content-Type", "application/json")
            .build();

        this.client.newCall(request)
            .execute()
            .then(result => {
                this.status = result.response.responseCode;
                Log.showInfo("Status : " + this.status);

                if (result.response.result)
                    this.content = result.response.result;
                else
                    this.content = result.response;

                Log.showInfo("Content : " + this.content);

                var newauthor = JSON.parse(result.response.result);

                Log.showInfo("New Author Id : " + newauthor.data.mAuthorId.toString()
                + ", Name : " + newauthor.data.mAuthorName.toString()
                + ", Email Id : " + newauthor.data.mAuthorEmailId.toString()
                + ", Password : " + newauthor.data.mAuthorPassword.toString());
            })
            .catch(err => {
                Log.showInfo("Error occurred - " + err.data);
                this.content = err.data;
            });
    },

    cancelRunningCall() {
        var request = new httpclient.Request.Builder()
            .get(this.commonServer)
            .tag("tag123")
            .addHeader("Content-Type", "application/json")
            .build();
        this.client.newCall(request).enqueue(this.onComplete, this.onError);
        this.client.cancelRequestByTag("tag123");
    },

    cancelQueuedCall() {
        let request1 = new httpclient.Request.Builder()
            .url(this.echoServer)
            .post(httpclient.RequestBody.create("This is just a test message"))
            .tag("tag1")
            .addHeader("Content-Type", "application/json")
            .build();
        this.client.newCall(request1).enqueue(this.onComplete1, this.onError1);

        let request2 = new httpclient.Request.Builder()
            .url(this.echoServer)
            .post(httpclient.RequestBody.create("This is just a hello world message"))
            .tag("tag2")
            .addHeader("Content-Type", "application/json")
            .build();
        this.client.newCall(request2).enqueue(this.onComplete2, this.onError2);

        let request3 = new httpclient.Request.Builder()
            .get(this.commonServer)
            .tag("tag3")
            .addHeader("Content-Type", "application/json")
            .build();
        this.client.newCall(request3).enqueue(this.onComplete3, this.onError3);

        let request4 = new httpclient.Request.Builder()
            .url(this.commonServer)
            .post(httpclient.RequestBody.create("This is just a repeated hello world message"))
            .tag("tag4")
            .addHeader("Content-Type", "application/json")
            .build();
        this.client.newCall(request4).enqueue(this.onComplete4, this.onError4);
        this.client.cancelRequestByTag("tag3");
    },
    onCallbackComplete: function (result) {
        if(result.body) {
            this.content = JSON.stringify( result.body);
            Log.showInfo("onCallbackComplete -> result : " + result.body + " ,type is : "
            + typeof result.body + " , code:" + result.code + " , header:" + result.header);
        }else
        Log.showInfo("onCallbackComplete -> result : " + JSON.stringify(result.response));
    },
    onCallbackError: function (error) {
        Log.showInfo("onCallbackError -> error : " + error);
        this.content = JSON.stringify(error);
    },
    JSONcallback() {
        Log.showInfo("JSONcallback -> ");
        var Callback = new httpclient.JsonCallback();
        Log.showInfo("JSONcallback -> 2 ");
        this.content = "waiting for response";
        let request1 = new httpclient.Request.Builder()
            .get(this.commonServer)
            .tag("tag_callbackJSON")
            .addHeader("Content-Type", "application/json")
            .convertor(Callback)
            .build();
        this.client.newCall(request1).execute().then(this.onCallbackComplete)
            .catch(this.onCallbackError);
    },
    Stringcallback() {
        Log.showInfo("Stringcallback -> ");
        var Callback = new httpclient.StringCallback();
        Log.showInfo("Stringcallback -> 2 ");
        this.content = "waiting for response";
        let request1 = new httpclient.Request.Builder()
            .get(this.commonServer)
            .tag("tag_callbackString")
            .addHeader("Content-Type", "application/json")
            .convertor(Callback)
            .build();
        this.client.newCall(request1).execute().then(this.onCallbackComplete)
            .catch(this.onCallbackError);
    },
    ByteStringcallback() {
        Log.showInfo("Stringcallback -> ");
        var Callback = new httpclient.ByteStringCallback();
        Log.showInfo("Stringcallback -> 2 ");
        this.content = "waiting for response";
        let request1 = new httpclient.Request.Builder()
            .get(this.commonServer)
            .tag("tag_callbackByte")
            .addHeader("Content-Type", "application/json")
            .convertor(Callback)
            .build();
        this.client.newCall(request1).execute().then(this.onCallbackComplete)
            .catch(this.onCallbackError);
    }
}